var Koa = require('koa'),
    DB = require('../module/db.js'),

    router = require('koa-router')(),

    user = require('./admin/user.js'),

    goods = require('./admin/goods.js'),

    focus = require('./admin/focus.js'),

    md5 = require('../module/tools.js'),

    jwt = require('koa-jwt'),

    addtoken = require('../module/token/addtoken.js');



//配置admin的子路由  层级路由
router.get('/', async (ctx)=>{
    await ctx.render('admin/index');
})

/**
 * @router POST /login
 * @desc   登录接口地址  返回
 */

router.post('/login',async (ctx)=>{
    let user = ctx.request.body,
        data = await DB.find('admin',{"username":user.username})
    ctx.body = data; 
    var password = user.password;
    //md5加密
    var md5Pass = await md5.MD5(password);
    //token中要携带的信息，自己定义
    let tk = addtoken(user); 
    try{
        if(!data[0]){
            ctx.body = {
                code: 0,
                status: false,
                msg:"账号错误"
            }
            return false;
        }
        // console.log(data[0].password , md5Pass)
        if(data[0].password != md5Pass){
            ctx.body = {
                code: 0,
                status: false,
                msg:"密码错误"
            }
            return false;
        }
        ctx.body = {
            code: 200,
            status: false,
            data: data[0],
            msg:"登录成功",
            token: tk
        }
    }catch(err){
        ctx.body = {
            code: 400,
            status: false,
            msg: err
        }
    }
})

/**
 * @router POST /menus
 * @desc   分类管理接口地址  返回
 */

router.get('/menus',async (ctx)=>{
    const menus = await DB.find('menus',"key");
    
    try {
        ctx.body = {
            code: 200,
            status: true,
            menus: menus
        }
    } catch (error) {
        ctx.body = {
            code: 400,
            status: false,
            msg: "获取失败"
        }
    }
})

router.use('/user',user);
router.use('/goods',goods);
module.exports=router.routes();
